package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.domain.Systemdictionaryitem;
import cn.wolfcode.quest.JsonResult;
import cn.wolfcode.quest.QueryObject;
import cn.wolfcode.result.PageResult;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.service.ISystemdictionaryitemService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("/role")
@Controller
public class RoleController {
    @Autowired
    private ISystemdictionaryitemService systemdictionaryitemService;


    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    public String showList(Model model, @ModelAttribute("qo") QueryObject qo){
        //调用service的query方法,将qo封装为PageResult
        PageInfo<Role> query = roleService.query(qo);
        List<Systemdictionaryitem> list = systemdictionaryitemService.selectBySn("payout");
        //添加到作用域
        model.addAttribute("pageResult", query);
        model.addAttribute("payouts",list);

        //转到视图
        return "role/list";
    }

    @RequestMapping("/input")
    public String input(Role role,Model model){
        //查询出所有权限数据
        List<Permission> permissions = permissionService.selectAll();
        //判断有无id
        if (role.getId()!=null){
            //有id查询出数据库的相关信息
            Role role1 = roleService.get(role.getId());
            //设置到作用域用于回显
            model.addAttribute("role", role1);

        }

        //无id直接重定向到input

        //将权限列表传进
        model.addAttribute( "permissions", permissions);
        return "role/input";

    }

    @RequestMapping("/saveOrUpdate")
    //接收参数,保存角色信息and角色-权限表信息
    public String saveOrUpdate(Role role,Long[] ids){
        //如果传来的角色对象有id则为更新,无id则为添加
        if (role.getId()!=null){
            roleService.updatePer(role, ids);
            return "redirect:/role/list.do";
        }
        //如果为添加时,添加所有数据
        roleService.insertPer(role, ids);

        //最后转到list
        return "redirect:/role/list.do";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        JsonResult jsonResult = new JsonResult();
        System.out.println(id);
        try {
            roleService.deleteByPrimaryKey(id);
            return jsonResult;
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMsg("删除失败");
            return jsonResult;
        }
    }

}
